package com.zzyl.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.DeviceDataPageReqDto;
import com.zzyl.entity.DeviceData;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeviceDataMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.runner.IotContent;
import com.zzyl.service.DeviceDataService;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.vo.DeviceVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DeviceDataServiceImpl implements DeviceDataService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void processIotMessage(String content) {
        if (StrUtil.isEmpty(content)){
            return;
        }
        //1. 将设备上报的json数据,转化为Java对象
        IotContent iotContent = JSONUtil.toBean(content, IotContent.class);
        //2. 获取设备上报的指标数据,封装对象
        Map<String,IotContent.Item> items = iotContent.getItems();
        if (CollectionUtil.isEmpty(items)){
            return;
        }
        // 查询设备详情
        DeviceVo deviceVo = deviceMapper.queryByIotId(iotContent.getIotId());
        if (ObjectUtil.isEmpty(deviceVo)){
            return;
        }
        //3. 保存到数据库
        List<DeviceData> deviceDataList =new ArrayList<>();
        items.forEach((key,item)->{
            DeviceData deviceData = new DeviceData();
            deviceData.setDeviceName(iotContent.getDeviceName());
            deviceData.setIotId(iotContent.getIotId());
            deviceData.setNickname(deviceVo.getNickname());
            deviceData.setProductKey(iotContent.getProductKey());
            deviceData.setProductName(deviceVo.getProductName());
            deviceData.setFunctionId(key);
            deviceData.setAccessLocation(deviceVo.getBindingLocation().toString());
            deviceData.setPhysicalLocationType(deviceVo.getPhysicalLocationType());
            deviceData.setDeviceDescription(deviceVo.getDeviceDescription());
            deviceData.setDataValue(String.valueOf(item.getValue()));
            deviceData.setAlarmTime(LocalDateTimeUtil.of(item.getTime()));
            deviceDataList.add(deviceData);
        });
        //将最新的数据保存在redis中
        redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,iotContent.getIotId(),JSONUtil.toJsonStr(deviceDataList));
        deviceDataMapper.insertBatch(deviceDataList);
    }

    @Override
    public PageResponse<DeviceDataVo> dataList(DeviceDataPageReqDto deviceDataPageReqDto) {
        String deviceName = deviceDataPageReqDto.getDeviceName();
        String functionId = deviceDataPageReqDto.getFunctionId();
        if (StrUtil.isEmpty(deviceName)||StrUtil.isEmpty(functionId)){
            throw new BaseException(BasicEnum.PARAMETER_MISSING);
        }
        LocalDateTime startDate = deviceDataPageReqDto.getStartDate();
        LocalDateTime endDate = deviceDataPageReqDto.getEndDate();
        LocalDateTime startTime = startDate == null? LocalDateTimeUtil.offset(LocalDateTime.now(),-1, ChronoUnit.HOURS):LocalDateTimeUtil.of(startDate);
        LocalDateTime endTime = endDate == null? LocalDateTime.now():LocalDateTimeUtil.of(endDate);
        PageHelper.startPage(deviceDataPageReqDto.getPageNum(),deviceDataPageReqDto.getPageSize());
        Page<DeviceData> page = deviceDataMapper.dataList(deviceName,functionId,startTime,endTime);
        return PageResponse.of(page,DeviceDataVo.class);
    }
}
